<?php

class DetailsSummaryExtension {
	const ATTRS_TO_KEEP = [ 'class', 'style' ];

	// Register any render callbacks with the parser
	public static function onParserFirstCallInit( Parser $parser ) {
		// When the parser sees the <sample> tag, it executes renderTagSample (see below)
		$parser->setHook( 'details', [ self::class, 'renderTagDetails' ] );
		$parser->setHook( 'summary', [ self::class, 'renderTagSummary' ] );
	}

	// Render <details>
	public static function renderTagDetails( $input, array $args, Parser $parser, PPFrame $frame ) {
		return self::renderHtml5Tag('details', $input, $args, $parser, $frame);
	}

	// Render <summary>
	public static function renderTagSummary( $input, array $args, Parser $parser, PPFrame $frame ) {
	return self::renderHtml5Tag('summary', $input, $args, $parser, $frame);
	}
	
	// Render a HTML5 tag that needs to be simply passed through
	public static function renderHtml5Tag($tagName, $input, array $args, Parser $parser, PPFrame $frame ) {
		$output = $parser->recursiveTagParse( $input, $frame );
		
		$resultAttrs = [];
		foreach (self::ATTRS_TO_KEEP as $argName) {
			if ( isset( $args[ $argName ] ) ) {
				$val = htmlspecialchars( $args[ $argName ] );
				$resultAttrs[] = $argName . '="' . $val . '"';
			}
		}
		
		$args = '';
		if ( count($resultAttrs) > 0 ) {
		  $args = ' ' . implode(' ', $resultAttrs);
		}
		
		return "<{$tagName}{$args}>" . $output . "</{$tagName}>";
	}
}